package com.atues.kuangshengjuc.add;

public class CountDownLatchDemo {
    public static void main(String[] args) {
        //创建一个CountDownLatch对象，初始计数为3
        java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(3);

        //创建三个线程，每个线程执行完后都会调用countDown()方法
        for (int i = 0; i < 4; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "完成任务");
                countDownLatch.countDown(); // 任务完成，计数减1
            }, "线程" + i).start();
        }

        try {
            countDownLatch.await(); // 等待所有线程完成
            System.out.println("所有任务完成，继续执行主线程");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
